<template>
  <div class="layout">
    <a-layout :style="{ height: '100%', backgroundColor: 'transparent' }">
      <a-layout-header>
        <Head
          who="local"
          @on-handleUser="setUser"
          @on-setGeneral="setGeneral"
          @on-handlePassword="handlePassword"
          @on-handleLog="handleLog"
          @on-about="aboutVisible = true"
      /></a-layout-header>
      <a-layout-content><router-view /></a-layout-content>
    </a-layout>

    <ModalSlot
      :visible="userModalVisible"
      title="用户信息"
      @handleCancel="userCancel"
      :width="600"
    >
      <div class="modal--box--wrap">
        <a-form :form="form1">
          <a-form-item label="姓名">
            <a-input
              :maxLength="30"
              :disabled="userInfo.level === 1 || userInfo.level === 5"
              autoComplete="off"
              v-decorator="[
                'name',
                {
                  rules: [
                    { required: true, message: '请输入姓名!' },
                    {
                      pattern: /^[0-9a-zA-Z.\u4e00-\u9fa5]*$/,
                      message: '姓名格式不正确,使用英文、中文、数字或组合!',
                    },
                  ],
                  initialValue: userInfo.name,
                },
              ]"
            />
          </a-form-item>
          <a-form-item label="账号">
            <a-input
              :maxLength="10"
              :disabled="userInfo.level === 1 || userInfo.level === 5"
              autoComplete="off"
              v-decorator="[
                'user',
                {
                  rules: [
                    { required: true, message: '请输入账号!' },
                    {
                      pattern: /^[0-9a-zA-Z]*$/,
                      message: '账号格式不正确,使用英文、数字或组合!',
                    },
                  ],
                  initialValue: userInfo.user,
                },
              ]"
            />
          </a-form-item>

          <!-- <a-form-item label="密码">
          <a-input-password
            :disabled="userInfo.level === 5"
            v-decorator="[
              'passwd',
              {
                rules: [
                  { required: true, message: '请输入密码!' },
                  {
                    pattern: /^\S+$/,
                    message: '密码中不能带有空格!',
                  },
                ],
                initialValue: _decrypt(userInfo.passwd),
              },
            ]"
          />
        </a-form-item> -->

          <a-form-item label="电话">
            <a-input
              :maxLength="30"
              autoComplete="off"
              v-decorator="[
                'tel',
                {
                  rules: [
                    {
                      pattern: /^1[3,4,5,6,7,8,9][0-9]{9}$/,
                      message: '请输入正确的手机号',
                    },
                  ],
                  initialValue: userInfo.tel,
                },
              ]"
            />
          </a-form-item>

          <a-form-item label="邮箱">
            <a-input
              :maxLength="30"
              autoComplete="off"
              v-decorator="[
                'email',
                {
                  rules: [
                    {
                      pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
                      message: '请输入正确的邮箱',
                    },
                  ],
                  initialValue: userInfo.email,
                },
              ]"
            />
          </a-form-item>

          <a-form-item label="电子签名">
            <MyUpload
              :sign="sign"
              @on-change="handleSignChange"
              :imgServerUrl="imgServerUrl"
              :userId="userInfo.id"
            />
          </a-form-item>
        </a-form>
        <div class="modal--box--footer--con">
          <a-space size="large">
            <button @click="userCancel" class="modal-btn cancal">取消</button>
            <button @click="userSubmit" class="modal-btn">确定</button>
          </a-space>
        </div>
      </div>
    </ModalSlot>
    <ModalSlot
      :visible="generalVisible"
      title="通用设置"
      @handleCancel="hispitalrCancel"
      :width="600"
    >
      <template
        v-if="
          userInfo.level === 1 || userInfo.level === 5 || userInfo.level === 2
        "
      >
        <a-tabs :active-key="tabKey" @change="tabcallback">
          <a-tab-pane key="2">
            <span slot="tab">
              <a-icon type="setting" />
              模板设置
            </span>
            <!-- <div class="form--work">
              <a-space size="large">
                <download-excel
                  class="download-excel"
                  :fields="json_fields"
                  worksheet="检测报告模板"
                  name="检测报告模板"
                  :fetch="getExcelData"
                  :before-finish="downExcelFinish"
                >
                  <a-button>下载模板</a-button>
                </download-excel>
                <ExUpload @getResult="getUploadData" />
                <SearchUpload
                  @getResult="getSearchUploadData"
                  :status="isSearchImport"
                  @changeStatus="changeSearchStatus"
                />
              </a-space>
            </div> -->
            <div class="modal--box--wrap2">
              <FormWork :status="generalVisible" />
            </div>
          </a-tab-pane>
        </a-tabs>
      </template>
    </ModalSlot>
    <ModalSlot
      :visible="passwordVisible"
      title="修改密码"
      @handleCancel="passwordCancel"
      :width="600"
    >
      <div class="modal--box--wrap">
        <a-form :form="form3">
          <a-form-item label="原密码">
            <a-input-password
              autoComplete="off"
              v-decorator="[
                'oldPassword',
                {
                  rules: [
                    { required: true, message: '请输入密码!' },
                    {
                      pattern:
                        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&_])[A-Za-z\d@$!%*?&_]{8,}$/,
                      message:
                        '密码长度至少为8并且包含大小写字母与特殊字符及数字,例如:Zxc_123456!',
                    },
                  ],
                },
              ]"
            />
          </a-form-item>

          <a-form-item label="新密码">
            <a-input-password
              autoComplete="off"
              v-decorator="[
                'passwd',
                {
                  rules: [
                    { required: true, message: '请输入密码!' },
                    {
                      pattern:
                        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&_])[A-Za-z\d@$!%*?&_]{8,}$/,
                      message:
                        '密码长度至少为8并且包含大小写字母与特殊字符及数字,例如:Zxc_123456!',
                    },
                    {
                      validator: validateToNextPassword,
                    },
                  ],
                },
              ]"
            />
          </a-form-item>

          <a-form-item label="确认密码">
            <a-input-password
              autoComplete="off"
              v-decorator="[
                'confirm',
                {
                  rules: [
                    { required: true, message: '请输入密码!' },
                    {
                      pattern:
                        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&_])[A-Za-z\d@$!%*?&_]{8,}$/,
                      message:
                        '密码长度至少为8并且包含大小写字母与特殊字符及数字,例如:Zxc_123456!',
                    },
                    {
                      validator: compareToFirstPassword,
                    },
                  ],
                },
              ]"
              @blur="handleConfirmBlur"
            />
          </a-form-item>
        </a-form>
        <div class="modal--box--footer--con">
          <a-space size="large">
            <button @click="passwordCancel" class="modal-btn cancal">
              取消
            </button>
            <button @click="passwordSubmit" class="modal-btn" v-preventReClick>
              确定
            </button>
          </a-space>
        </div>
      </div>
    </ModalSlot>
    <ModalSlot
      :visible="logVisible"
      title="操作日志"
      @handleCancel="logVisible = false"
      :width="600"
    >
      <div class="modal--box--wrap2">
        <a-table
          class="log-table"
          :pagination="false"
          :columns="logColumns"
          :data-source="logTableData"
          :row-key="(record) => record.id"
          :loading="logLoading"
          :rowClassName="
            () => {
              return 'blue';
            }
          "
          :locale="{ emptyText: '暂无数据' }"
        >
        </a-table>
        <div class="pagination--box">
          <a-config-provider :locale="locale">
            <a-pagination
              v-model="current"
              :total="total"
              :page-size="pageSize"
              @change="handleTableChange"
            >
            </a-pagination>
          </a-config-provider>
        </div>
        <div class="log--btn2">
          <button @click="exportLog" class="modal-btn cancal2">导出</button>
          <button @click="logVisible = false" class="modal-btn cancal">
            关闭
          </button>
        </div>
      </div>
    </ModalSlot>
    <ModalSlot
      :visible="aboutVisible"
      title="关于"
      @handleCancel="aboutVisible = false"
      @handleOk="aboutVisible = false"
      :width="600"
    >
      <ul class="about--wrap">
        <li class="about--wrap--item">
          <span class="about--wrap--item-sub">软件发布版本: </span>
          <span class="about--wrap--item-con">{{ aboutInfo.version }}</span>
        </li>
        <li class="about--wrap--item">
          <span class="about--wrap--item-sub">软件完整版本: </span>
          <span class="about--wrap--item-con">{{ aboutInfo.fullVersion }}</span>
        </li>
        <li class="about--wrap--item">
          <span class="about--wrap--item-sub">制造商: </span>
          <span class="about--wrap--item-con">{{
            aboutInfo.manufacturerx
          }}</span>
        </li>
        <li class="about--wrap--item">
          <span class="about--wrap--item-sub">联系电话: </span>
          <span class="about--wrap--item-con">{{ aboutInfo.tel }}</span>
        </li>
      </ul>
    </ModalSlot>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { encrypt, decrypt } from "@/utils/cryptoTools";
import { getBase64Image } from "@/utils/dellImg";
import MyUpload from "@/components/MyUpload";
import Head from "@/components/Head";
import ModalSlot from "@/components/ModalSlot";
import { updateUser, loginOut } from "@/api/login";
import { bulkCreateSymptomSubAndSym } from "@/api/SymptomSub";
import { getAllSymptom } from "@/api/symptom";
import { v4 as uuidv4 } from "uuid";
import { bulkCreateSearch } from "@/api/searchInfo";
import FormWork from "@/components/FormWork";
import { logColumns } from "@/utils";
import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
import moment from "moment";
import { getLogInfo, getAllLogInfo, addLogInfo } from "@/api/logInfo";
import Idle from "idle-js";
import { exportXlsxFile } from "@/utils/exportFile";
// import ExUpload from "@/components/ExUpload";
// import SearchUpload from "@/components/SearchUpload";
export default {
  name: "Layout",
  data() {
    return {
      userModalVisible: false, //用户信息
      passwordVisible: false, //修改密码
      generalVisible: false, //通用设置
      aboutVisible: false, //关于
      logVisible: false, //日志
      form1: this.$form.createForm(this, { name: "user" }),
      form3: this.$form.createForm(this, { name: "password" }),
      sign: "", //用户电子签名
      tabKey: "2",
      json_fields: {
        模板分类: "subject",
        症状: "symptom",
        超声影像所见: "seen",
        超声影像诊断提示: "tips",
      },
      isSearchImport: false,
      locale: zhCN,
      total: 0,
      current: 1,
      pageSize: 10,
      logLoading: false,
      logColumns: logColumns,
      logTableData: [],
      idle: null,
    };
  },
  components: {
    MyUpload,
    Head,
    ModalSlot,
    // ExUpload,
    // SearchUpload,
    FormWork,
  },
  computed: {
    ...mapState([
      "userInfo",
      "SERVERBASE_URL",
      "imgServerUrl",
      "aboutInfo",
      "idleTime",
    ]),
  },
  mounted() {
    this.idle = new Idle({
      idle: this.idleTime || 600000, // 10分钟 = 600000 毫秒
      onIdle: this.handleOnIdle,
      onActive: this.handleOnActive,
      keepTracking: true,
      startAtIdle: false,
    });
    this.idle.start();
  },
  methods: {
    //用户设置
    setUser() {
      console.log(
        "%c [ setUser ]-37",
        "font-size:13px; background:pink; color:#bf2c9f;",
        "setUser"
      );
      this.userModalVisible = true;
      const user = {};
      user.name = this.userInfo.name;
      user.user = this.userInfo.user;
      user.passwd = this._decrypt(this.userInfo.passwd);
      user.tel = this.userInfo.tel;
      user.email = this.userInfo.email;
      this.sign = this.userInfo.sign;
    },

    //通用设置
    setGeneral() {
      console.log(
        "%c [ setGeneral ]-41",
        "font-size:13px; background:pink; color:#bf2c9f;",
        "setGeneral"
      );
      this.generalVisible = true;
    },
    //用户确认修改
    userSubmit(e) {
      e.preventDefault();
      const vm = this;
      this.form1.validateFields(async (err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          const userInfo = {
            ...values,
            sign: vm.sign,
            // passwd: encrypt(values.passwd),
          };
          if (!vm.sign) {
            userInfo.sign_url = "";
          } else {
            const imgBase64 = await getBase64Image(vm.sign);
            userInfo.sign_url = imgBase64;
          }
          const res = await updateUser(
            this.SERVERBASE_URL,
            vm.userInfo.id,
            userInfo
          );
          if (res.code == 200) {
            try {
              vm.$store.commit("SET_USERINFO", res.data);
              vm.$message.success("成功！");
              vm.userModalVisible = false;
            } catch (err) {
              console.log(err);
            }
          } else {
            if (res.err) {
              vm.$message.error(`${res.err}`);
            } else {
              vm.$message.error(`账户已存在!`);
            }
          }
        }
      });
    },
    //用户取消修改
    userCancel(e) {
      if (e) {
        e.preventDefault();
      }
      this.form1.resetFields();
      if (this.sign) {
        this.sign = "";
      }
      this.userModalVisible = false;
    },
    //通用取消修改
    hispitalrCancel(e) {
      if (e) {
        e.preventDefault();
      }
      if (this.logo) {
        this.logo = "";
      }
      this.generalVisible = false;
    },
    //电子签名
    handleSignChange(sign) {
      this.sign = sign;
    },
    tabcallback(data) {
      this.tabKey = data;
    },
    //获取数据库已有的模板
    async getExcelData() {
      const res = await getAllSymptom(this.SERVERBASE_URL);
      if (res.code == 200) {
        return res.data;
      } else {
        return [
          {
            subject: "腹部",
            symptom: "胆结石",
            seen: "胆囊@切面形态大小正常;形态饱满，切面大小约×mm@，@壁薄、光滑，;壁厚约mm，稍毛糙，@其腔内可见@一个强回声团;几个强回声团;多个强回声团;一不规则强回声区@，@大小约×mm;较大的约×mm;范围约×mm@，@改变体位可移动;改变体位无明显移动;形态可随体位改变@，后方伴声影。胆总管、肝内外胆管未见明显扩张。",
            tips: "@胆囊结石;胆囊多发性结石;胆囊泥沙样结石",
          },
        ];
      }
    },
    //下载完成回调
    downExcelFinish() {
      this.$message.success(`下载完成!`);
    },
    //获取导入数据
    async getUploadData(data) {
      console.log("导入数据", data);
      if (!data || data.length == 0) {
        this.$message.warning("数据为空！请填写数据！");
        return;
      }
      let key = false;
      let errInfo;
      data.forEach((item) => {
        if (!item["模板分类"] && !item["症状"] && !item["超声影像所见"]) {
          errInfo = `存在空的模板分类！空的症状！空的超声影像所见！`;
          key = true;
        } else if (
          !item["模板分类"] &&
          !item["症状"] &&
          !item["超声影像诊断提示"]
        ) {
          errInfo = `存在空的模板分类！空的症状！空的超声影像诊断提示！`;
          key = true;
        } else if (!item["模板分类"] && !item["症状"]) {
          errInfo = "存在空的模板分类！与空的症状！";
          key = true;
        } else if (!item["超声影像所见"] || !item["超声影像诊断提示"]) {
          errInfo = `${item["模板分类"]}某个值为空！`;
          key = true;
        } else if (!item["症状"]) {
          errInfo = `${item["模板分类"]}的症状值为空！`;
          key = true;
        } else if (!item["模板分类"]) {
          errInfo = "存在空的模板分类！";
          key = true;
        }
      });
      if (key) {
        this.$message.warning(`${errInfo}`);
        return;
      }

      const SymSubs = [];
      const SymS = [];
      const hadSymSu = {};
      data.forEach((item) => {
        if (!hadSymSu[item["模板分类"]]) {
          let symptomsubId = uuidv4();
          let symSubItem = {
            id: symptomsubId,
            title: item["模板分类"],
          };
          let symItem = {
            id: uuidv4(),
            title: item["症状"],
            seen: item["超声影像所见"],
            tips: item["超声影像诊断提示"],
            symptomsubId,
          };
          hadSymSu[item["模板分类"]] = symptomsubId;
          SymS.push(symItem);
          SymSubs.push(symSubItem);
        } else {
          let symItem = {
            id: uuidv4(),
            title: item["症状"],
            seen: item["超声影像所见"],
            tips: item["超声影像诊断提示"],
            symptomsubId: hadSymSu[item["模板分类"]],
          };
          SymS.push(symItem);
        }
      });

      console.log(hadSymSu);

      const res = await bulkCreateSymptomSubAndSym(this.SERVERBASE_URL, {
        SymSubs,
        SymS,
      });
      if (res.code === 200) {
        console.log("导入数据", res.data);
        this.$message.success(`导入成功!`);
      } else {
        this.$message.error(`导入失败!`);
      }
    },
    //获取导入常用词库数据
    async getSearchUploadData(data) {
      console.log("导入数据", data);
      if (!data || data.length == 0) {
        this.$message.warning("数据为空！请填写数据！");
        this.isSearchImport = false;
        return;
      }
      let searchArr = [];
      data.forEach((item) => {
        if (item["数据类型"] == "词库" && !item["拼音码"]) {
          this.$message.warning(`存在空的搜索词库拼音码！`);
          this.isSearchImport = false;
          return;
        }
        let searchItem = {
          id: uuidv4(),
          type: item["数据类型"] == "符号" ? "symbol" : "word",
          pinyin: item["拼音码"] ? item["拼音码"] : "",
          detail: item["详细内容"],
        };
        searchArr.push(searchItem);
      });
      const res = await bulkCreateSearch(this.SERVERBASE_URL, searchArr);
      if (res.code === 200) {
        console.log("导入数据", res.data);
        this.isSearchImport = false;
        this.$message.success(`导入成功!`);
      } else {
        this.isSearchImport = false;
        this.$message.error(`导入失败!`);
      }
    },
    //导入常用词库状态改变
    changeSearchStatus() {
      this.isSearchImport = true;
    },
    _decrypt(data) {
      return decrypt(data);
    },
    //密码修改
    handlePassword() {
      this.passwordVisible = true;
    },
    //修改密码确认
    passwordSubmit(e) {
      e.preventDefault();
      this.form3.validateFields(async (err, values) => {
        if (!err) {
          console.log("Received values of form: ", values);
          const vm = this;
          let decode = this._decrypt(vm.userInfo.passwd);
          if (values.oldPassword === decode) {
            const res = await updateUser(vm.SERVERBASE_URL, vm.userInfo.id, {
              passwd: encrypt(values.passwd),
            });
            if (res.code == 200) {
              try {
                vm.$message.success("修改密码成功！");
                this.form3.resetFields();
                vm.passwordVisible = false;
                vm.$router.push({ name: "Login" });
              } catch (err) {
                console.log(err);
              }
            } else {
              vm.$message.error(`${res.err}`);
            }
          } else {
            this.$message.error("原密码错误，请检查！");
          }
        }
      });
    },
    //密码修改取消
    passwordCancel(e) {
      if (e) {
        e.preventDefault();
      }
      this.form3.resetFields();
      this.passwordVisible = false;
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.form3;
      if (value && value !== form.getFieldValue("passwd")) {
        callback("两次输入的密码不一致");
      } else {
        callback();
      }
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.form3;
      if (value && this.confirmDirty) {
        form.validateFields(["confirm"], { force: true });
      }
      callback();
    },
    //操作日志
    handleLog() {
      this.getLogInfoData();
      this.logVisible = true;
    },
    //logData当前页码改变的回调
    handleTableChange(pagination) {
      this.current = pagination;
      this.getLogInfoData();
    },
    //获取Log数据
    async getLogInfoData() {
      let params = {
        total: this.total,
        current: this.current,
        pageSize: this.pageSize,
      };
      const res = await getLogInfo(this.SERVERBASE_URL, params);
      if (res.code === 200) {
        this.logLoading = false;
        this.total = res.data.count;
        this.logTableData = res.data.rows.map((item) => {
          item.createdAt = moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss");
          return item;
        });
      } else {
        console.log(res);
      }
    },
    loginOut() {
      const vm = this;
      const name = this.userInfo.name;
      loginOut(this.SERVERBASE_URL, name)
        .then((res) => {
          if (res.code == 200) {
            vm.$router.push({ name: "Login" });
            vm.$store.commit("INITSTATE");
            window.sessionStorage.clear();
            window.localStorage.clear();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleOnIdle() {
      console.log("闲置10分钟！");
      this.loginOut();
    },
    handleOnActive() {
      console.log("激活!");
    },
    //导出日志
    async exportLog() {
      try {
        let totalLog;
        const res = await getAllLogInfo(this.SERVERBASE_URL);
        if (res.code === 200) {
          totalLog = res.data.rows.map((item) => {
            item.createdAt = moment(item.createdAt).format(
              "YYYY-MM-DD HH:mm:ss"
            );
            if(item.content){
              const con = JSON.parse(item.content);
              item.content = con.res;
              item.sNo = con.sNo;
            }
            return item;
          });
        } else {
          console.log(res);
          return;
        }

        if (totalLog.length == 0) {
          return;
        }
        const headerMapping = {
          createdAt: "操作时间",
          name: "用户名",
          type: "类别",
          event: "操作事件",
          content: "内容",
          sNo:"受试者筛选号"
        };
        const fileName = `日志-${moment().format("YYYY-MM-DD HH:mm:ss")}`;
        exportXlsxFile(totalLog, headerMapping, fileName, "");
        console.log("导出日志", totalLog);
        addLogInfo(this.SERVERBASE_URL, {
          name: this.userInfo.name,
          type: "操作",
          event: "导出日志",
        });
      } catch (error) {
        console.log("exportLog error", error);
      }
    },
  },
  beforeDestroy() {
    if (this.idle) {
      this.idle.stop();
      this.idle = null;
    }
  },
};
</script>

<style scoped lang="less">
@import "~@/assets/css/layout.less";
</style>
